<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left" class="picking-form">
      <el-divider content-position="left">基本信息</el-divider>
      <el-row :gutter="24">
        <el-col :sm="12" :xs="24">
          <el-form-item label="工单ID" prop="orderId">
            <el-input v-model="form.orderId" placeholder="请输入工单ID" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="领料日期" prop="issueDate">
            <el-date-picker clearable v-model="form.issueDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择领料日期" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="审核状态" prop="reviewStatus">
            <el-select v-model="form.reviewStatus" placeholder="请选择审核状态">
              <el-option label="未审核" value="未审核" />
              <el-option label="已审核" value="已审核" />
              <el-option label="驳回" value="驳回" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="创建人" prop="creator">
            <el-input v-model="form.creator" placeholder="请输入创建人" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">物料信息</el-divider>
      <el-row :gutter="24">
        <el-col :sm="12" :xs="24">
          <el-form-item label="物料编码" prop="materialId">
            <el-input v-model="form.materialId" placeholder="请输入物料编码" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="form.materialName" placeholder="请输入物料名称" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="物料规格" prop="specification">
            <el-input v-model="form.specification" placeholder="请输入物料规格" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="物料单位" prop="materialUnit">
            <el-input v-model="form.materialUnit" placeholder="请输入物料单位" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">数量信息</el-divider>
      <el-row :gutter="24">
        <el-col :sm="12" :xs="24">
          <el-form-item label="需求数量" prop="requiredQty">
            <el-input v-model.number="form.requiredQty" type="number" min="0" placeholder="请输入需求数量" @input="handleRequiredQuantityChange" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="实际领料数量" prop="issuedQty">
            <el-input v-model.number="form.issuedQty" type="number" min="0" placeholder="请输入实际领料数量" @input="handleActualQuantityChange" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">单据信息</el-divider>
      <el-row :gutter="24">
        <el-col :sm="12" :xs="24">
          <el-form-item label="单据名称" prop="documentName">
            <el-input v-model="form.documentName" placeholder="请输入单据名称" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="单据编号" prop="documentNumber">
            <el-input v-model="form.documentNumber" placeholder="请输入单据编号" />
          </el-form-item>
        </el-col>
        <el-col :sm="24" :xs="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin: 16px 0 0 0;">
      <picking-detail-table v-model="form.details" ref="pickingDetailTable" />
    </div>
    <div class="dialog-footer" style="margin-top: 32px; text-align: center;">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { addPicking } from '@/api/picking/picking'
import { updateInventory, getInventory } from '@/api/storage/inventory'
import { getUserProfile } from '@/api/system/user'
// 库存获取由子表组件负责，这里不再直接依赖库存接口
import PickingDetailTable from '@/views/picking_detail/picking_detail/PickingDetailTable.vue'
import eventBus from '@/utils/eventBus';

export default {
  name: 'PickingAdd',
  meta: { title: '新增领料' },
  components: { PickingDetailTable },
  data() {
    return {
      form: {
        orderId: null,
        materialId: null,
        documentName: null,
        issueDate: null,
        specification: null,
        reviewStatus: null,
        materialName: null,
        requiredQty: null,
        issuedQty: null,
        documentNumber: null,
        materialUnit: null,
        remarks: null,
        creator: null,
        details: []
      },
      rules: {}
    }
  },
  created() {
    // 检查是否有从生产页面传递过来的参数
    this.initFormFromQuery();
  },
  // 监听路由变化，当路由参数改变时重新初始化数据
  watch: {
    '$route'(to, from) {
      // 如果路由参数发生变化，重新初始化表单
      if (to.query.orderId !== from.query.orderId) {
        this.resetForm();
        this.initFormFromQuery();
      }
    }
  },
  methods: {
    /** 重置表单数据 */
    resetForm() {
      this.form = {
        orderId: null,
        materialId: null,
        documentName: null,
        issueDate: null,
        specification: null,
        reviewStatus: null,
        materialName: null,
        requiredQty: null,
        issuedQty: null,
        documentNumber: null,
        materialUnit: null,
        remarks: null,
        creator: null,
        details: []
      };
      // 清除表单验证状态
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    /** 从URL参数初始化表单数据 */
    initFormFromQuery() {
      const query = this.$route.query;
      if (query.orderId) {
        // 先清空子表数据，确保没有缓存
        this.form.details = [];
        
        // 从生产页面传递过来的数据
        this.form.orderId = query.orderId;
        this.form.materialId = query.materialId || '';
        this.form.materialName = query.materialName || '';
        this.form.specification = '标准规格'; // 提供默认规格
        this.form.materialUnit = '个'; // 默认单位
        this.form.issueDate = new Date().toISOString().split('T')[0]; // 当前日期
        this.form.reviewStatus = '未审核';
        
        // 计算需求数量：工单数量 - 已完成数量
        const orderQuantity = parseInt(query.orderQuantity) || 0;
        const completedQuantity = parseInt(query.completedQuantity) || 0;
        this.form.requiredQty = Math.max(0, orderQuantity - completedQuantity);
        this.form.issuedQty = 0;
        
        // 生成单据信息
        this.form.documentName = `工单${query.orderId}领料单`;
        this.form.documentNumber = `PL-${Date.now()}`;
        this.form.remarks = `从工单${query.orderId}生成，物料：${query.materialName || ''}`;
        
        // 通过API获取用户信息
        getUserProfile().then(response => {
          const userData = response.data;
          console.log('用户详细信息:', userData);
          
          // 优先使用昵称，如果没有则使用用户名，如果用户名是admin则显示"系统管理员"
          let creatorName = userData.nickName || userData.userName || '系统';
          if (creatorName === 'admin') {
            creatorName = '系统管理员';
          }
          this.form.creator = creatorName;
          
          // 自动添加一条物料记录到子表
          this.addMaterialToDetails(query);
          
          this.$message.success('已自动填充工单信息，请确认后提交');
        }).catch(error => {
          console.error('获取用户信息失败:', error);
          // 如果API调用失败，使用store中的数据作为备选
          const userName = this.$store.getters.name;
          const nickName = this.$store.getters.nickName;
          let creatorName = nickName || userName || '系统';
          if (creatorName === 'admin') {
            creatorName = '系统管理员';
          }
          this.form.creator = creatorName;
          
          // 自动添加一条物料记录到子表
          this.addMaterialToDetails(query);
          
          this.$message.success('已自动填充工单信息，部分字段已设置默认值，库存数量请根据实际库存情况填写后提交');
        });
      }
    },
    /** 添加物料到子表 */
    addMaterialToDetails(query) {
      const orderQuantity = parseInt(query.orderQuantity) || 0;
      const completedQuantity = parseInt(query.completedQuantity) || 0;
      const requiredQty = Math.max(0, orderQuantity - completedQuantity);
      
      const materialDetail = {
        id: null,
        // 物料主键和编码/名称要对应，确保库存查询能正确过滤
        materialId: query.materialId ? Number(query.materialId) : null,
        materialCode: query.materialCode || '',
        materialName: query.materialName || '',
        materialSpec: '标准规格', // 提供默认规格
        unit: '个', // 默认单位
        attribute: '生产物料', // 提供默认属性
        batchNumber: `BATCH-${Date.now()}`, // 生成批号
        warehouse: '', // 默认为空
        location: 'A-01-01', // 提供默认库位
        requiredQuantity: requiredQty,
        actualQuantity: 0, // 初始实发数量为0
        stockQuantity: null, // 库存数量需要从库存系统获取，暂时设为null
        sourceDocument: `WO-${query.orderId}`,
        sourceOrder: `PO-${query.orderId}`,
        remark: `从工单${query.orderId}生成`,
        createTime: null,
        updateTime: null,
        parentId: null
      };
      
      // 先添加到子表
      this.form.details.push(materialDetail);
      // 库存获取改为点击“获取库存”按钮时再触发（不在此处自动获取）
    },
    
    /** 处理实际领料数量变化，同步更新子表实发数量 */
    handleActualQuantityChange(value) {
      // 确保子表存在且有数据
      if (this.form.details && this.form.details.length > 0) {
        // 更新所有子表行的实发数量
        this.form.details.forEach(detail => {
          detail.actualQuantity = value || 0;
        });
        
        // 通过ref调用子表组件的方法更新实发数量
        if (this.$refs.pickingDetailTable) {
          this.$refs.pickingDetailTable.updateActualQuantity(value);
        }
        
        // 触发子表更新
        this.$nextTick(() => {
          this.$emit('update:details', this.form.details);
        });
      }
    },
    
    /** 处理需求数量变化，同步更新子表需求数量 */
    handleRequiredQuantityChange(value) {
      // 确保子表存在且有数据
      if (this.form.details && this.form.details.length > 0) {
        // 更新所有子表行的需求数量
        this.form.details.forEach(detail => {
          detail.requiredQuantity = value || 0;
        });
        
        // 通过ref调用子表组件的方法更新需求数量
        if (this.$refs.pickingDetailTable) {
          this.$refs.pickingDetailTable.updateRequiredQuantity(value);
        }
        
        // 触发子表更新
        this.$nextTick(() => {
          this.$emit('update:details', this.form.details);
        });
      }
    },
    
    /** 验证库存充足性 */
    async validateStockAvailability() {
      if (!this.form.details || this.form.details.length === 0) {
        return { isValid: false, message: '请先添加物料明细' };
      }
      
      const validationResults = [];
      
      for (const detail of this.form.details) {
        if (detail.inventoryId) {
          try {
            // 获取最新库存信息
            const inventoryRes = await getInventory(detail.inventoryId);
            const inventory = inventoryRes.data;
            
            if (!inventory) {
              validationResults.push({
                material: detail.materialName || detail.materialCode,
                isValid: false,
                message: '无法获取库存信息'
              });
              continue;
            }
            
            // 计算可用库存 = 当前库存 - 锁定库存
            const availableStock = Number(inventory.quantity || 0) - Number(inventory.lockedQuantity || 0);
            const requiredQty = Number(detail.requiredQuantity || 0);
            
            if (requiredQty > availableStock) {
              validationResults.push({
                material: detail.materialName || detail.materialCode,
                isValid: false,
                message: `库存不足！需求：${requiredQty}，可用库存：${availableStock}`,
                availableStock,
                requiredQty,
                shortage: requiredQty - availableStock
              });
            } else {
              validationResults.push({
                material: detail.materialName || detail.materialCode,
                isValid: true,
                availableStock,
                requiredQty
              });
            }
          } catch (error) {
            console.error('获取库存信息失败:', error);
            validationResults.push({
              material: detail.materialName || detail.materialCode,
              isValid: false,
              message: '获取库存信息失败'
            });
          }
        } else {
          validationResults.push({
            material: detail.materialName || detail.materialCode,
            isValid: false,
            message: '请先选择库存'
          });
        }
      }
      
      // 检查是否有库存不足的情况
      const insufficientStock = validationResults.filter(result => !result.isValid);
      
      if (insufficientStock.length > 0) {
        return {
          isValid: false,
          message: '库存验证失败',
          details: insufficientStock,
          hasInsufficientStock: true
        };
      }
      
      return {
        isValid: true,
        message: '库存验证通过',
        details: validationResults
      };
    },
    
    /** 处理库存不足的情况 */
    handleInsufficientStock(validationResult) {
      const insufficientItems = validationResult.details;
      let message = '库存数量不足，请及时采购！\n\n';
      
      insufficientItems.forEach(item => {
        message += `物料：${item.material}\n`;
        message += `需求数量：${item.requiredQty}\n`;
        message += `可用库存：${item.availableStock}\n`;
        message += `缺口数量：${item.shortage}\n\n`;
      });
      
      message += '是否立即生成采购订单？';
      
      this.$confirm(message, '库存不足提醒', {
        confirmButtonText: '生成采购订单',
        cancelButtonText: '稍后处理',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        // 跳转到采购订单生成页面
        this.generatePurchaseOrder(insufficientItems);
      }).catch(() => {
        this.$message.info('请及时处理库存不足问题');
      });
    },
    
    /** 生成采购订单 */
    generatePurchaseOrder(insufficientItems) {
      // 构造采购订单数据
      const purchaseOrderData = {
        orderType: '紧急采购',
        sourceDocument: `领料单-${this.form.documentNumber}`,
        materials: insufficientItems.map(item => ({
          materialId: item.materialId,
          materialName: item.materialName,
          requiredQuantity: item.shortage,
          unit: item.unit || '个'
        })),
        priority: '高',
        remarks: `因库存不足自动生成，来源：${this.form.documentNumber}`
      };
      
      // 跳转到采购订单页面
      this.$router.push({
        path: '/purchase/purchase/add',
        query: {
          autoGenerated: 'true',
          purchaseData: JSON.stringify(purchaseOrderData)
        }
      });
    },
    
  
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 提交前进行库存充足性验证
          const stockValidation = await this.validateStockAvailability();
          
          if (!stockValidation.isValid) {
            if (stockValidation.hasInsufficientStock) {
              // 库存不足，提示用户并询问是否生成采购订单
              this.handleInsufficientStock(stockValidation);
            } else {
              // 其他验证失败
              this.$message.error(`库存验证失败：${stockValidation.message}`);
            }
            return;
          }
          
          // 库存验证通过，继续提交
          addPicking(this.form).then(async response => {
            try {
              const details = Array.isArray(this.form.details) ? this.form.details : [];
              const deductionTasks = details
                .filter(d => d.inventoryId && d.requiredQuantity && d.requiredQuantity > 0)
                .map(async d => {
                  try {
                    // 拉取最新库存，防止并发导致的旧值覆盖
                    const invRes = await getInventory(d.inventoryId);
                    const inv = invRes && invRes.data ? invRes.data : { id: d.inventoryId, quantity: 0, lockedQuantity: 0 };
                    const currentQty = Number(inv.quantity) || 0;
                    const deductQty = Number(d.requiredQuantity) || 0;
                    const newQty = Math.max(0, currentQty - deductQty);
                    const payload = { ...inv, id: inv.id, quantity: newQty };
                    return updateInventory(payload);
                  } catch (e) {
                    // 单条失败不中断其他条，但给出提示
                    console.error('扣减库存失败', d, e);
                    this.$message.error(`扣减库存失败：${d.materialName || d.materialCode || ''}`);
                  }
                });
              await Promise.all(deductionTasks);
              this.$modal.msgSuccess("新增成功，库存已按需求数量扣减")
              
              // 发送库存刷新事件，通知库存管理页面刷新数据
              eventBus.$emit('refresh-inventory');
            } catch (e) {
              console.error('扣减库存过程出错', e);
              this.$modal.msgSuccess("新增成功，但库存扣减可能失败，请检查库存")
              
              // 即使扣减失败，也发送刷新事件，确保库存管理页面显示最新数据
              eventBus.$emit('refresh-inventory');
            }
            // 新增成功返回上一级
            this.$router.back()
          })
        }
      })
    },
    //取消按钮
    cancel() {
      //取消之后返回上一级
      this.$router.back()
    }
  }
}
</script>

<style scoped>
.picking-form {
  background: #fff;
  padding: 24px 18px 8px 18px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(41,128,185,0.08);
}
</style> 
